package cn.com.utt.common.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import cn.com.utt.common.service.SendEmailService;
import cn.com.utt.common.sms.zt.EmailAccount;
@Service("sendEmailService")
public class SendEmailServiceImpl implements SendEmailService{
	private static List<EmailAccount> emailAccounts = new ArrayList<EmailAccount>();
	private static String from = "support@reosware.com";
	@Value("${emailAccount}")
	private String emailAccount;
	@Value("${emailPasswd}")
	private  String emailPasswd;
	@Value("${smtp}")
	private  String smtp;
	@Value("${from}")
	private  String froms;
	
	public void init(){
		String accounts = emailAccount;
		String smtps = smtp;
		String passwds = emailPasswd;
		from =froms;
		if(accounts!=null&&smtps!=null&&passwds!=null){
			String[] account = accounts.split(" ");
			String[] smtp = smtps.split(" ");
			String[] passwd = passwds.split(" ");
			for (int i = 0; i < account.length; i++) {
				EmailAccount e = new EmailAccount();
				e.setAccount(account[i]);
				e.setSmtp(smtp[i]);
				e.setPasswd(passwd[i]);
				emailAccounts.add(e);
			}
		}
	}
//	static
//		{
//			String accounts = emailAccount;
//			String smtps = smtp;
//			String passwds = emailPasswd;
//			System.out.println(accounts+"   "+smtps+"  "+passwds);
//			from = froms;
//			if(accounts!=null&&smtps!=null&&passwds!=null){
//				String[] account = accounts.split(" ");
//				String[] smtp = smtps.split(" ");
//				String[] passwd = passwds.split(" ");
//				for (int i = 0; i < account.length; i++) {
//					EmailAccount e = new EmailAccount();
//					e.setAccount(account[i]);
//					e.setSmtp(smtp[i]);
//					e.setPasswd(passwd[i]);
//					emailAccounts.add(e);
//				}
//			}
			
//		}
	public EmailAccount getAccount() {
		init();
		if (emailAccounts.size() > 1) {
			int index = (int) Math.round(Math.random() * (emailAccounts.size()-1));
			return emailAccounts.get(index);
		} else {
			return null;
		}
	}

	@Override
	public boolean sendEmail(String to, String subject, String content) {
		final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
		EmailAccount account = getAccount();
		if (account == null) {
			return false;
		}
		Properties props = new Properties();
		props.put("mail.smtp.host", account.getSmtp()); // 指定SMTP服务器
		props.put("mail.smtp.auth", "true");// 指定是否需要SMTP验证
		props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        //邮箱发送服务器端口,这里设置为465端口
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        
		try {
			Session mailSession = Session.getDefaultInstance(props);
			mailSession.setDebug(false);// 是否在控制台显示debug信息
			Message message = new MimeMessage(mailSession);
			
			Address from_address = new InternetAddress(account.getAccount(), from);    
			message.setFrom(from_address); // 发件人
			String[] emails = to.split(",");
			for (int i = 0; i < emails.length; i++) {
				if (!emails[i].equals("")) {
					message.addRecipient(Message.RecipientType.TO,
							new InternetAddress(emails[i])); // 收件人
				}
			}

			message.setSubject(subject); // 邮件主题
			String htmlcontent = content;
			if (!htmlcontent.equals("") ) { // html格式或者包括附件
				Multipart container = new MimeMultipart();
				MimeBodyPart tBodyPart;
				if (!"".equals(htmlcontent)) { // 邮件的html内容
					tBodyPart = new MimeBodyPart();
					tBodyPart.setContent(htmlcontent, "text/html; charset=GBK");
					container.addBodyPart(tBodyPart);
				}
				message.setContent(container); // 加入html和附件
			}
			message.saveChanges();
			Transport transport = mailSession.getTransport("smtp");
			System.out.println(account.getSmtp()+","+account.getAccount()+","+
					account.getPasswd());
//			maillogger.info(account.getAccount()+","+to+","+subject);
			transport.connect(account.getSmtp(), account.getAccount(),
					account.getPasswd());

			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

}
